import { Injectable } from '@nestjs/common';
import { ApiProperty } from '@nestjs/swagger';
import { createCipheriv, createDecipheriv, scrypt } from 'crypto';
import { IV, SECRET } from 'src/constants/crypto';
import { promisify } from 'util';
import { BufferRes } from './crypt.controller';

@Injectable()
export class CryptService {
    async encrypt(textToEncrypt): Promise<Buffer> {
        const key = (await promisify(scrypt)(SECRET, 'salt', 32)) as Buffer;
        const cipher = createCipheriv('aes-256-ctr', key, IV);
        const encryptedText = Buffer.concat([
            cipher.update(textToEncrypt),
            cipher.final(),
        ]);
        return encryptedText;
    }

    async decrypt(encryptedText: BufferRes) {
        const key = (await promisify(scrypt)(SECRET, 'salt', 32)) as Buffer;
        const decipher = createDecipheriv('aes-256-ctr', key, IV);
        const decryptedText = Buffer.concat([
            decipher.update(Buffer.from(encryptedText.data)),
            decipher.final(),
        ]);
        return decryptedText.toString();
    }
}
